package com.oms.web.controller.order;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oms.common.core.domain.AjaxResult;
import com.oms.common.core.page.PageDomain;
import com.oms.common.core.page.TableDataInfo;
import com.oms.common.core.page.TableSupport;
import com.oms.common.utils.StringUtils;
import com.oms.common.utils.sql.SqlUtil;
import com.oms.framework.util.ShiroUtils;
import com.oms.system.domain.OmsOrder;
import com.oms.system.domain.OrderGroup;
import com.oms.system.domain.SysUser;
import com.oms.system.service.IOmsOrderService;
import com.oms.system.service.IOrderStatusDeptService;
import com.oms.system.service.ISysRoleService;
import com.oms.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import sun.misc.Cache;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 订单管理
 * @author lucas
 * @studio andot
 * @date 2019-09-08 18:10:36
 */
@Api(tags="订单操作")
@Controller
@RequestMapping("/order")
public class OrderController {

    @Resource
    private IOmsOrderService orderService;
    @Autowired
    private ISysUserService userService;
    @Resource
    private IOrderStatusDeptService orderStatusDeptService;
    @Autowired
    private ISysRoleService roleService;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @GetMapping("")
    public String index(){
        return "order/index";
    }

    @GetMapping("add")
    public String add(){
        return "order/add";
    }

    @GetMapping("edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        mmap.put("orderId", id);
        return "order/edit";
    }

    @GetMapping("orderStatus/{id}")
    public String orderStatus(@PathVariable("id") Long id, ModelMap mmap) {
        mmap.put("orderId", id);
        return "order/orderStatus";
    }

    @GetMapping("orderInfo/{id}")
    public String orderInfo(@PathVariable("id") Long id, ModelMap mmap) {
        mmap.put("orderId", id);
        return "order/orderInfo";
    }

    @ApiOperation(value = "获取订单列表")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo getOrderList(OmsOrder omsOrder) throws ParseException {
        if(omsOrder.getOrderTimeStr() != null && !omsOrder.getOrderTimeStr().equals("")){
            omsOrder.setOrderTime(sdf.parse(omsOrder.getOrderTimeStr()));
        }
        if(omsOrder.getSendTimeStr() != null && !omsOrder.getSendTimeStr().equals("")){
            omsOrder.setSendTime(sdf.parse(omsOrder.getSendTimeStr()));
        }
        startPage();
        Long userId = ShiroUtils.getUserId();
        SysUser sysUser = userService.selectUser(userId);
        List<Integer> ids = orderStatusDeptService.getDeptList(sysUser.getDeptId()).stream().map(item->{
            return item.getOrderStatus();
        }).collect(Collectors.toList());
        Set<String> roles = roleService.selectRoleKeys(userId);
        List<OmsOrder> list = orderService.getOrderList(omsOrder, ids, roles.contains("admin"));
        return getDataTable(list);
    }

    @ApiOperation(value = "獲取订单")
    @GetMapping("/{id}")
    @ResponseBody
    public AjaxResult getOrderProductById(@PathVariable("id") Long id){
        try{
            return AjaxResult.success(orderService.getOrderProductById(id));
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "添加订单")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addOrder(@RequestBody OrderGroup orderGroup) throws ParseException {
        orderGroup.getOrder().setOrderTime(simpleDateFormat.parse(orderGroup.getOrderTimeStr()));
        orderGroup.getOrder().setSendTime(simpleDateFormat.parse(orderGroup.getSendTimeStr()));
        try{
            orderService.insertOrder(orderGroup.getOrder(), orderGroup.getOrderProduct());
            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "更新订单")
    @PutMapping("/{id}")
    @ResponseBody
    public AjaxResult updateOrder(@PathVariable("id") Long id, @RequestBody OrderGroup orderGroup){
        try{
            orderGroup.getOrder().setId(id);
            orderGroup.getOrderProduct().setOrderId(id);
            orderService.updateOrder(orderGroup.getOrder(), orderGroup.getOrderProduct());
            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "更新订单状态")
    @PutMapping("/status/{id}")
    @ResponseBody
    public AjaxResult updateOrder(@PathVariable("id") Long id, Integer orderStatus){
        try{
            orderService.updateOrderStatus(id, orderStatus);
            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除订单")
    @DeleteMapping("/{id}")
    @ResponseBody
    public AjaxResult delOrder(@PathVariable("id") Long id){
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        try{
            orderService.deleteOrder(ids);
            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "批量删除订单")
    @DeleteMapping("/batch")
    @ResponseBody
    public AjaxResult delBatchOrder(@RequestBody List<Long> ids){
        try{
            orderService.deleteOrder(ids);
            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}
